import React, { useState, useEffect } from "react";
import { Tree } from "antd";
import { getPermissionList } from "@/api/role";

const defaultPermissionList = [
  {
    id: 1,
    name: "首页",
  },
  {
    id: 2,
    name: "拍品管理",
    children: [
      {
        id: 3,
        name: "拍品列表",
      },
      {
        id: 4,
        name: "分类管理",
      },
    ],
  },
];
const RoleTree = ({ value, onChange }) => {
  const [permissionList, setPermissionList] = useState([]);
  const [checkedKeys, setCheckedKeys] = useState(() => {
    return value || [];
  });

  const fetchPermissionList = async () => {
    const res = await getPermissionList();
    setPermissionList(res.data);
  };

  useEffect(() => {
    fetchPermissionList();
  }, []);

  useEffect(() => {
    setCheckedKeys(value || []);
  }, [value]);

  return (
    <Tree
      checkable
      fieldNames={{
        key: "id",
        title: "name",
        children: "children",
      }}
      checkedKeys={checkedKeys}
      onSelect={(permissionIds) => {
        setCheckedKeys(permissionIds);
        onChange(permissionIds);
      }}
      onCheck={(permissionIds) => {
        setCheckedKeys(permissionIds);
        onChange(permissionIds);
      }}
      treeData={permissionList}
    />
  );
};

export default RoleTree;
